package com.flower.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.flower.domain.ApiResult;
import com.flower.domain.entity.User;
import com.flower.domain.user.UserParam;
import com.flower.domain.user.UserRegisterParam;
import com.flower.service.UserService;
import com.flower.utils.ItUtil;
import com.flower.utils.JwtUtil;
import com.flower.utils.RedisUtils;
import com.flower.utils.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/reception/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 前台会员的登录功能
     * @param param
     * @return 返回一个jwt 即token值
     */
    @PostMapping("/login")
    public ApiResult<Map<String,Object>> login(@RequestBody UserParam param){
        //将传入的值 在数据库进行查询
        //1.构建lambdaquerwrapper
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,param.getName());
        //使用md5进行密码加密 再进行数据库密码比较
        wrapper.eq(User::getPassword,DigestUtils.md5DigestAsHex(param.getPassword().getBytes()));
        //如果数据库中并未查询到该用户数据 直接抛出运行时异常即可
        User one = userService.getOne(wrapper);
        if(Objects.isNull(one)){
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 将用户信息 放入redis中
        redisUtils.set("login_id:"+one.getUid(),one);
        log.warn("redis的key是:{}","login_id:"+one.getUid());
        //调用jwt工具类 生成token
        String jwt = JwtUtil.createJWT(one.getUid().toString(),24*60 * 60 * 1000L);
        Map map = new LinkedHashMap(2);
        map.put("token",jwt);
        return ApiResult.ok(map,"登录成功");
    }


    /**
     * 获取会员信息
     * @return
     */
    @GetMapping("/info")
    public ApiResult<User> userInfo(){
        //获取线程里面的id
        Long id = Long.valueOf(String.valueOf(ThreadUtils.get()));
        //根据id查询出 此用户的信息
        User byId = userService.getById(id);
        return ApiResult.ok(byId);
    }


    /**
     * 前台会员退出登录
     * @return
     */
    @GetMapping("/logout")
    public ApiResult<Boolean> logout(){
        //获取线程里面的id
        String userId = String.valueOf(ThreadUtils.get());
        //删除redis里面的信息
        redisUtils.del(userId);
        return ApiResult.ok();
    }


    /**
     * 获取验证码接口
     * @return
     */
    @GetMapping("/code")
    public ApiResult<String> getCode(@RequestParam String phone){
        //判断redis里是否已经有验证码了 如果有直接返回即可
        Object o = redisUtils.get(phone + "yzm");
        if(!Objects.isNull(o)){
            return ApiResult.ok((String) o,"验证码10分钟内有效");
        }
        //使用验证码工具类生成随机的6位验证码
        String verifyCode = ItUtil.createVerifyCode(6);
        //将验证码存储至 redis中
        redisUtils.set(phone + "yzm",verifyCode,60*10);
        return ApiResult.ok(verifyCode);
    }

    /**
     * 注册接口
     * @return
     */
    @PostMapping("/register")
    public ApiResult<Boolean> register(@RequestBody UserRegisterParam param){
        //验证前台传过来的号码 是否已经注册了 (直接在数据库设置唯一值也是可以的)
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,param.getUserName());
        User one = userService.getOne(wrapper);
        if(!Objects.isNull(one)){
            throw new RuntimeException("该号码已经被注册了，请换一个号码");
        }
        //看验证码是否与前端传来的是否一致 不一致 提醒用户重新获取验证码
        Object o = redisUtils.get("yzm");
        if(Objects.isNull(o)){
            throw new RuntimeException("验证码已过期，请重新生成");
        }
        if(!param.getCode().equalsIgnoreCase(String.valueOf(o))){
            throw new RuntimeException("验证码不一致，请验证过后重试");
        }
        //对用户类进行一些属性的初始化
        User user = new User();
        user.setUserName(param.getUserName());
        user.setPassword(DigestUtils.md5DigestAsHex(param.getPassword().getBytes()));
        user.setPhone(param.getPhone());
        user.setAvatar("http://lixinghe.meimeng.eu.org/flower/image/favction.jpg");
        userService.save(user);
        return ApiResult.ok();
    }



}
